import React from 'react';
import menuRoute from 'routes/menuRoute'
import { connect } from 'react-redux';
import { randomString , messages, deepFullCopy } from "share/common";
import { Tree, Spin, message, Icon, Button } from 'antd';
const TreeNode = Tree.TreeNode;
import noInfoImg from 'images/no-info.png'
import docService from 'containers/help-center-user/doc/doc.service'
import 'styles/doc/doc.scss'

class Doc extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      contentLoading: false,
      refreshLoading: false,
      menuList: [],
      menuDataList: [], //菜单数据列表，用于前后切换文档
      menuIdList: [],  //菜单数据id列表，用于前后切换文档
      info: {},
      treeKey: 0,
      selectedTreeID: null,
      expandedKeys: [],
      docList: menuRoute.getRouteItem('doc'),
      content: null,//右侧文章内容
      linkId: props.linkId,
    }
  }

  componentWillMount() {
    this.getMenuList();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.params.linkId && (this.props.params.linkId !== nextProps.params.linkId)) {
      this.setState({
        selectedTreeID: nextProps.params.linkId,
      }, () => {
        this.getDocInfo();
      })
    }
  }

  //获取目录列表
  getMenuList = () => {
    const {expandedKeys} = this.state;
    this.setState({ loading: true });
    docService.getMenuList().then(res => {
      if (res.data && res.data.length) {
        let menuDataList = [];
        let menuIdList = [];
        let firstId = res.data[0].id;
        let getMenuDataList = arr => {
          arr.map(item => {
            menuDataList.push(item);
            menuIdList.push(item.id);
            item.children && getMenuDataList(item.children)
          })
        };
        getMenuDataList(res.data);
        if(this.props.params.linkId !== ":linkId"){
          let linkId = this.props.params.linkId;
          let item = this.mapArrayFindId(res.data, linkId);
          item.parentId !== "0" && this.mapArrayFindExpandedKeys(res.data, item);
          this.setState({
            menuList: res.data,
            loading: false,
            selectedTreeID: linkId,
            expandedKeys,
            menuDataList,
            menuIdList
          }, () => {
            this.getDocInfo();
          })
        }else{
          let item = this.mapArrayFindId(res.data, firstId);
          item.parentId !== "0" && this.mapArrayFindExpandedKeys(res.data, item);
          this.setState({
            loading: false,
            menuList: res.data,
            selectedTreeID: firstId,
            expandedKeys,
            menuDataList,
            menuIdList
          }, () => {
            this.getDocInfo();
          })
        }
      } else {
        this.setState({ loading: false })
      }
    }).catch(() => {
      this.setState({ loading: false })
    })
  };

  //获取文档信息
  getDocInfo = () => {
    let params = {
      documentContentId: this.state.selectedTreeID
    };
    this.setState({ contentLoading: true });
    docService.getDocDetail(params).then(res => {
      this.setState({
        contentLoading: false,
        info: res.data
      }, () => {
        this.renderText(this.state.info.docContent);
        this.node.scrollIntoView();
      });
    }).catch(() => {
      this.setState({ contentLoading: false })
    })
  };

  //选择目录
  onTreeSelect = (key) => {
    const {treeKey, menuList} = this.state;
    let expandedKeys = this.state.expandedKeys;
    if (key && key.length) {
      let item = this.mapArrayFindId(menuList, key[0]);
      if(item.children && item.children.length){
        expandedKeys.addIfNotExist(key[0]);
      }
      this.setState({
        selectedTreeID: key[0],
        treeKey: treeKey + 1,
        expandedKeys,
      }, () => {
        this.getDocInfo();
      })
    }
  };

  //上一篇／下一篇
  viewLastOrNextDoc = (isLast) => {
    let { menuDataList, selectedTreeID, expandedKeys } = this.state;
    expandedKeys = [];
    menuDataList.map((item, index) => {
      if (item.id === selectedTreeID) {
        if (item.children && item.children.length && !isLast) { //下一篇文档是当前文档的儿子
          expandedKeys.push(selectedTreeID);
        } else { //下一篇文档是当前文档的兄弟或长辈，且若下一篇文档的父节点没展开
          let expandedSourceParent = isLast ? menuDataList[index - 1].parentId : menuDataList[index + 1].parentId;
          let loopMenuDataList = parentId => {
            this.state.menuDataList.map(dataItem => {
              if (dataItem.id === parentId) {
                expandedKeys.indexOf(dataItem.id) === -1 && expandedKeys.push(dataItem.id);
                if (!dataItem.parentId || dataItem.parentId !== "0") { //下一篇文档的父节点不是一级的
                  loopMenuDataList(dataItem.parentId)
                }
              }
            })
          };
          loopMenuDataList(expandedSourceParent);
        }
        this.setState({
          selectedTreeID: isLast ? menuDataList[index - 1].id : menuDataList[index + 1].id,
          expandedKeys
        }, () => {
          this.getDocInfo();
        })
      }
    })
  };

  //获取上一篇／下一篇的文档名称
  getLastOrNextTitle = (isLast) => {
    const { menuDataList, selectedTreeID } = this.state;
    return menuDataList.map((item, index) => {
      if (item.id === selectedTreeID) {
        return isLast ? (menuDataList[index - 1] || {}).docTitle : (menuDataList[index + 1] || {}).docTitle
      }
    })
  };

  //渲染目录树
  renderTree = (data) => {
    return data.map(item => {
      return (
        <TreeNode key={item.id} title={<div className="menu-title">{item.docTitle}</div>}>
          {item.children && item.children.length ? this.renderTree(item.children) : ''}
        </TreeNode>
      )
    })
  };

  //点击文档内容
  handleClickContent = e => {
    let href = e.target.getAttribute('href');
    if (href && href.split('?linkId=')[1]) { //文档跳转链接
      e.preventDefault();
      let linkId = href.split('?linkId=')[1];
      if (this.state.menuIdList.indexOf(linkId) === -1) {
        message.warning(messages('doc.key3')/*您没有权限查看该文档*/)
      } else {
        this.onTreeSelect([linkId])
      }
    }
  };

  //刷新
  handleRefresh = () => {
    this.setState({ refreshLoading: true });
    docService.refreshDoc().then(() => {
      this.setState({ refreshLoading: false });
      this.getMenuList()
    }).catch(() => {
      this.setState({ refreshLoading: false })
    })
  };

  //递归遍历查找menuList中的id为某值的元素
  mapArrayFindId = (arr, id) => {
    for(let i = 0; i < arr.length; i++){
      if(arr[i].id === id){
        return arr[i];
      }
      if(arr[i].children && arr[i].children.length){
        let res = this.mapArrayFindId(arr[i].children, id);
        if(res){
          return res;
        }
      }
    }
  };

  mapArrayFindExpandedKeys = (arr, item) => {
    const {expandedKeys} = this.state;
    if(item.parentId){
      expandedKeys.addIfNotExist(item.parentId);
      this.setState({
        expandedKeys,
      }, () => {
        let parent = this.mapArrayFindId(arr, item.parentId);
        parent.parentId !== "0" && this.mapArrayFindExpandedKeys(arr, parent);
      });
    }else{
      expandedKeys.addIfNotExist(item);
      this.setState({expandedKeys})
    }
  };

  onExpand = (expandedKeys, expanded) => {
    this.setState({expandedKeys})
  };

  /*
  * 这里主要对文章中的宽度超过720px的图片进行等比例缩放 至宽度720 高度为h的图片
  * */
  renderText = (content) => {
    let text = content;
    let flag = 0;
    if(text){
      let imgs = text.match(/<img.*?src="(.*?)".*?>/ig);
      if(imgs && imgs.length){
        imgs.map((item) => {
          flag ++ ;
          let src = item.match(/src="(.*?)".*?/ig)[0].slice(5, -1);
          let img = new Image();
          // 获得图片尺寸，并根据比例调整显示高宽
          img.src = src;
          img.onload = () => {
            let {height, width} = img;  //图片尺寸
            let h = null;
            if(width > 720){
              h = parseInt(720 * (height/width));
              text = text.replace(item, `<img src=${src}  width="720px" height="${h}px" style="width: 720px; height: ${h}px;"/>`);
            }
            if(flag === imgs.length){
              this.setState({
                content: text,
              });
            }
          };
        });
      }else {
        this.setState({
          content: text,
        });
      }
    }else {
      this.setState({
        content: text,
      });
    }
  };


  render() {
    const { loading, contentLoading, menuList, info, selectedTreeID, menuIdList, expandedKeys, refreshLoading, treeKey,
      content} = this.state;
    let refreshBtnVisible = window.location.href.indexOf('uat') !== -1;
    return (
      <div className="doc" ref={node => this.node = node}>
        {loading ? <Spin/> : (
          menuList && menuList.length ? (
            <div className={"doc-container"}>
              <div className="menu-container">
                {/*因为uat环境的文档加了缓存，所以需要一个按钮手动清除缓存 from 宗云大佬*/}
                {refreshBtnVisible && (
                  <Button className="refresh-button"
                          loading={refreshLoading}
                          onClick={this.handleRefresh}
                          style={{marginBottom: 10}}>
                    <Icon type="reload" /> {messages('help-center-user.key21')/*刷新*/}
                  </Button>
                )}
                <Tree
                  className="draggable-tree"
                  selectedKeys={[selectedTreeID]}
                  key={treeKey}
                  expandedKeys={expandedKeys}
                  onSelect={this.onTreeSelect}
                  onExpand={this.onExpand}
                >
                  {this.renderTree(menuList)}
                </Tree>
              </div>
              <div className="info-container">
                <div className="info-container-content">
                  <div className="doc-content-left">
                    <div className="doc-content-left-icon">
                      {menuIdList.indexOf(selectedTreeID) !== 0 && (
                        <Icon type="left" className="doc-content-left-real-icon" onClick={() => this.viewLastOrNextDoc(true)}/>
                      )}
                    </div>
                  </div>
                  <div className={"real-content"}>
                    <div className={'content-wrap'}>
                      <div className={'content-inner'}>
                        <div className="doc-title">{info.docTitle}</div>
                        <Spin spinning={contentLoading}>
                          <div onClick={this.handleClickContent}>
                            <div dangerouslySetInnerHTML={{__html: content}} />
                          </div>
                        </Spin>
                      </div>
                    </div>
                  </div>
                  <div className="doc-content-right">
                    <div className="doc-content-right-icon">
                      {menuIdList.indexOf(selectedTreeID) !== menuIdList.length - 1 && (
                        <Icon type="right" className="doc-content-right-real-icon" onClick={() => this.viewLastOrNextDoc(false)}/>
                      )}
                    </div>
                  </div>
                  <div className={"clear"}/>
                </div>
              </div>
              <div className={"clear"}/>
            </div>
          ) : (
            <div className="no-doc">
              <img src={noInfoImg} />
              <div>{messages('doc.key6')/*当前没有文档*/}</div>
            </div>
          )
        )}
      </div>
    )
  }
}

Doc.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {

  }
}

export default connect(mapStateToProps)(Doc);
